package com.tsinghuabigdata.edu.ddmath.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.util.PreferencesUtils;

/**
 * 带ToolBar的RoboActivity
 */
public abstract class RoboForToolBarActivity extends AppCompatActivity {

    public static final String ACTION = "FINISH_ALL";

    private FinishReceiver mFinishReceiver;
    private SystemBarTintManager tintManager;

    private boolean userBarBackgroud = false;

    private MyToolBar mToolbar;
    private TextView leftTitle;
    private TextView title;
    private TextView righttitle;

    /**
     * 用户自定义状态栏背景
     *
     * @param use true: 使用activity布局作为背景  false：使用主题色作为背景
     */
    public void setUserBarBackgroud(boolean use) {
        this.userBarBackgroud = use;
        if (userBarBackgroud) {
            if (tintManager != null) {
                tintManager.setStatusBarTintResource(R.color.bar_tint);
            }
        }
    }

    protected abstract int getContentViewId();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_CustomToolbar_AppCompat);
        super.onCreate(savedInstanceState);

        setContentView(getContentViewId());

        mToolbar = (MyToolBar) findViewById(R.id.toolbar);
        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
            // 默认不显示原生标题
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            //initToolbar(new ToolbarHelper(mToolbar));


            leftTitle = (TextView) findViewById(R.id.toolbar_lefttitle);
            title = (TextView) findViewById(R.id.toolbar_title);
            righttitle = (TextView) findViewById(R.id.toolbar_righttitle);
            mToolbar.setBackgroundColor(getResources().getColor(R.color.bar_tint));

            //事件
            View.OnClickListener leftListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLeftClick();
                }
            };
            View.OnClickListener rightListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRightClick();
                }
            };

            //注册事件
            mToolbar.setNavigationOnClickListener(leftListener);
            leftTitle.setOnClickListener(leftListener);

            righttitle.setOnClickListener(rightListener);
        }

        initSystemBar(this);
        mFinishReceiver = new FinishReceiver();
        startMonitoring();

    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);

        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            getWindow().setStatusBarColor(Color.TRANSPARENT);

            if (hideTitle){
                ActionBar actionBar = getSupportActionBar();
                actionBar.hide();
            }

        } else*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            // 兼容4.4或以上的系统
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            // 底部虚拟按键高度
//            if(getSupportActionBar()!=null && OSUtils.isMeiZuBrand()) {
//                View view = ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
//                if ( view.getFitsSystemWindows() &&  getSupportActionBar().isShowing()) {
//                    int top = WindowUtils.getActionBarHeight(this) + WindowUtils.getStatusHeight(this);
//                    view.setFitsSystemWindows(false);
//                    ((FrameLayout.LayoutParams) view.getLayoutParams()).setMargins(0, top, 0, 0);
//                    view.requestLayout();
//                }
//            }
        }

    }

    protected void startMonitoring() {
        IntentFilter intentFilter = new IntentFilter(ACTION);
        registerReceiver(mFinishReceiver, intentFilter);
    }

    protected void stopMonitoring() {
        unregisterReceiver(mFinishReceiver);
    }

    /**
     * 关闭所有的Activity
     */
    public void finishAll() {
        sendBroadcast(new Intent(ACTION));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMonitoring();
    }

    public void onLeftClick() {
        //not implemented
        //subclass implemented
    }

    public void onRightClick() {
        //not implemented
        //subclass implemented
    }

    public void setRightTitle(CharSequence title) {
        righttitle.setText(title);
        if (title != null) {
            righttitle.setVisibility(View.VISIBLE);
        } else {
            righttitle.setVisibility(View.GONE);
        }
    }

    public void setRightTitle(CharSequence title, int color) {
        setRightTitle(title);
        righttitle.setTextColor(color);
    }

    public String getRightTitle() {
        return (String) righttitle.getText();
    }

    public TextView getRightBtn() {
        return righttitle;
    }

    public void setLeftTitle(CharSequence title) {
        setLeftTitle(title, true);
    }

    public void setLeftTitle(CharSequence title, boolean isshowLefticon) {
        this.leftTitle.setText(title);
        if (!TextUtils.isEmpty(title) && isshowLefticon) {
            if (mToolbar != null)
                mToolbar.setNavigationIcon(R.drawable.ic_back_white);
        } //默认没有导航图标
    }

    public void setLeftTitle(CharSequence title, int rId) {
        setLeftTitle(title);
        this.leftTitle.setTextColor(getResources().getColor(rId));
    }

//    public void setLeftIconShow(boolean show) {
//        if (show) {
//            if( mToolbar!=null )
//                mToolbar.setNavigationIcon( R.drawable.ic_back );
//        } else {
//            //left_icon.setVisibility(View.INVISIBLE);
//        }
//    }

    public CharSequence getLeftTitle() {
        return leftTitle.getText();
    }

//    public void setSecondLeftTile(CharSequence title) {
//        this.bar_second_left_btn.setText(title);
//        if (title != null) {
//            bar_second_left_btn.setVisibility(View.VISIBLE);
//        } else {
//            bar_second_left_btn.setVisibility(View.GONE);
//        }
//    }
//
//    public void setLeftCircleImg(int resId, boolean circle) {
//        left_img.setImageResource(resId);
//        left_img.setVisibility(View.VISIBLE);
//        if (!circle) {
//            // 不使用圆角样式
//            left_img.setUseDefaultStyle(true);
//            left_img.invalidate();
//        }
//    }
//
//    public void setLeftIcn(int resId) {
//        left_icon.setImageResource(resId);
//        left_icon.setVisibility(View.VISIBLE);
//    }

//    public CircleImageView getLeftIcon() {
//        return left_img;
//    }

    @Override
    public void setTitle(CharSequence title) {
        this.title.setText(title);
    }

    public void setTitle(CharSequence title, int colorId) {
        this.title.setText(title);
        this.title.setTextColor(getResources().getColor(colorId));
    }

    @Override
    public void setTitle(int titleId) {
        this.setTitle(getText(titleId));
    }

    private void initSystemBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(activity, true);

            tintManager = new SystemBarTintManager(activity);

            tintManager.setStatusBarTintEnabled(true);
            tintManager.setNavigationBarTintEnabled(true);
            // 使用颜色资源
            tintManager.setStatusBarTintColor(R.color.transparent);
            tintManager.setNavigationBarTintColor(R.color.transparent);
            // 使用颜色资源
        }

    }

    public void goUsercenter() {
        PreferencesUtils.putBoolean(getBaseContext(), AppConst.IS_USERCENTER_SHOW, true);
        finish();
    }
    public void goActivity(Class clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void goActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    @TargetApi(19)
    private void setTranslucentStatus(Activity activity, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void setBarTextcolor(int textcolorid) {
        title.setTextColor(getResources().getColor(textcolorid));
        leftTitle.setTextColor(getResources().getColor(textcolorid));
        righttitle.setTextColor(getResources().getColor(textcolorid));
    }

    /**
     * 退出监听
     */
    class FinishReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 监听退出消息
            if (intent.getAction() == ACTION) {
                finish();
            }
        }
    }

    public void setStatusbarBg(int colorid) {
        if (tintManager != null) {
            tintManager.setStatusBarTintResource(colorid);
        }
    }
}
